<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script> 
       //可以根据不同的触发条件，通知不同的观察者，而不是通知全部观察者
       //list      仓库: 存放订阅者
       //publish   发布
       //subscribe 订阅

       //调度中心
       const PubSub = {
          message:{},
          publish(type,data){
            if(!this.message[type].length) return console.log(type,'无订阅事件');
            this.message[type].forEach(item => item(data))
          },
          subscribe(type,cb){
             if(!this.message[type]){
                this.message[type] = [];
             }
             this.message[type].push(cb);
          },
          unsubscribe(type,cb){
            if(!this.message[type]) return;
            if(!cb) return this.message[type] = [];
            
            let key = this.message[type].indexOf(cb);
            if(key > -1) this.message[type].splice(key,1);
          }
       }
 

       function testA(data){
         console.log(data);
       }

       function testB(data){
         console.log(data);
       }

       PubSub.subscribe('A',testA)
       PubSub.subscribe('B',testB)
       PubSub.subscribe('B',testA)


       PubSub.publish('A','123');
       PubSub.publish('B','456');


       //取消订阅testA
       PubSub.unsubscribe('A',testA);
       PubSub.publish('A','123');
       //取消B所有订阅
       PubSub.unsubscribe('B');
       PubSub.publish('B');

    </script>
</body>
</html>